<!-- 关联出库单 -->
<template>
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" title="关联出库单" width="900" :close-on-click-modal="false"
            style="padding: 10px;">
            <!-- 搜索框 -->
            <div class="search-box">
                <el-input v-model="searchKeyword" placeholder="出库单号/客户名称" class="search-input" suffix-icon="Search"
                    @input="handleSearch" />
            </div>

            <!-- 表格 -->
            <el-table :data="tableData" border style="width: 100%" @row-click="handleRowClick" highlight-current-row
                v-loading="loading">
                <el-table-column width="50" align="center">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row.id"
                            @change="() => handleRadioChange(scope.row)">&nbsp;</el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="order_no" label="出库单号" align="center" width="auto" />
                <el-table-column prop="order_date" label="下单日期" align="center" width="auto" />
                <el-table-column prop="delivery_date" label="交货日期" align="center" width="auto" />
                <el-table-column prop="customer_name" label="客户" align="center" />
            </el-table>

            <!-- 分页 -->
            <div class="pagination-box">
                <el-pagination v-model:current-page="pageData.page" v-model:page-size="pageData.page_size"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="handleConfirm"
                        :disabled="!selectedOutboundOrder">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import api from '@/api';

const emit = defineEmits(['selectOutboundOrder']);

// 定义出库单数据类型
interface OutboundOrder {
    id: number;
    order_no: string;
    order_date: string;
    delivery_date: string;
    total_amount: string;
    customer_id: number;
    customer_name: string;
    customer_phone: string;
}

// 分页数据类型
interface PageData {
    page: number;
    page_size: number;
    keywords: string;
    list_type: number;
}

const dialogVisible = ref(false);
const searchKeyword = ref('');
const selectedRow = ref<number | string>('');
const selectedOutboundOrder = ref<OutboundOrder | null>(null);
const loading = ref(false);
const total = ref(0);

// 分页数据
const pageData = ref<PageData>({
    page: 1,
    page_size: 10,
    keywords: '',
    list_type: 2 // 根据接口文档，查询类型固定为2
});

// 表格数据
const tableData = ref<OutboundOrder[]>([]);

// 获取出库单列表数据
const getTableData = async () => {
    loading.value = true;
    try {
        const params = {
            ...pageData.value,
            keywords: searchKeyword.value
        };

        const res = await api.publicFun.getOutboundList(params);

        if (res.status && res.code === 200) {
            tableData.value = res.data.data || [];
            total.value = res.data.pager?.total_records || 0;
        } else {
            ElMessage.error(res.message || '获取出库单列表失败');
            tableData.value = [];
            total.value = 0;
        }
    } catch (error) {
        console.error('获取出库单列表失败:', error);
        ElMessage.error('获取出库单列表失败');
        tableData.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
};

// 搜索处理
const handleSearch = () => {
    pageData.value.page = 1; // 重置到第一页
    getTableData();
};

// 处理页面大小变化
const handleSizeChange = (val: number) => {
    pageData.value.page_size = val;
    pageData.value.page = 1;
    getTableData();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
    pageData.value.page = val;
    getTableData();
};

// 处理行点击事件
const handleRowClick = (row: OutboundOrder) => {
    selectedRow.value = row.id;
    selectedOutboundOrder.value = row;
};

// 处理单选按钮变化事件
const handleRadioChange = (row: OutboundOrder) => {
    selectedOutboundOrder.value = row;
};

// 处理确认按钮点击事件
const handleConfirm = () => {
    if (selectedOutboundOrder.value) {
        // 转换数据格式以匹配父组件期望的格式
        const orderData = {
            id: selectedOutboundOrder.value.id,
            orderNo: selectedOutboundOrder.value.order_no,
            customer: selectedOutboundOrder.value.customer_name,
            amount: selectedOutboundOrder.value.total_amount,
            orderDate: selectedOutboundOrder.value.order_date,
            deliveryDate: selectedOutboundOrder.value.delivery_date,
            customer_id: selectedOutboundOrder.value.customer_id,
            customer_phone: selectedOutboundOrder.value.customer_phone
        };

        emit('selectOutboundOrder', orderData);
        dialogVisible.value = false;
    } else {
        ElMessage.warning('请选择一个出库单');
    }
};

// 打开弹窗
const openDialog = (preSelectedOrder?: any) => {
    dialogVisible.value = true;
    searchKeyword.value = '';
    pageData.value.page = 1;
    pageData.value.page_size = 10;
    
    // 清除之前的选择状态
    selectedRow.value = '';
    selectedOutboundOrder.value = null;
    
    // 如果有预选的出库单，设置选中状态
    if (preSelectedOrder) {
        console.log('预选择的出库单:', preSelectedOrder);
        
        // 设置选中状态，支持不同的id字段格式
        const orderId = preSelectedOrder.id || preSelectedOrder.outbound_order_id;
        if (orderId) {
            selectedRow.value = orderId;
            selectedOutboundOrder.value = preSelectedOrder;
        }
    }
    
    getTableData();
};

// 监听弹窗显示状态
watch(dialogVisible, (newVal) => {
    if (newVal) {
        getTableData();
    }
});

// 监听表格数据变化，如果有预选项则在数据加载后设置选中状态
watch(tableData, () => {
    if (selectedRow.value && tableData.value.length > 0) {
        // 在表格数据中查找对应的记录
        const matchedOrder = tableData.value.find(item => 
            item.id === selectedRow.value || 
            item.order_no === (selectedOutboundOrder.value as any)?.orderNo ||
            item.order_no === selectedOutboundOrder.value?.order_no
        );
        
        if (matchedOrder) {
            selectedRow.value = matchedOrder.id;
            selectedOutboundOrder.value = matchedOrder;
            console.log('在表格中找到并选中预选项:', matchedOrder);
        }
    }
});

// 暴露方法
defineExpose({
    openDialog
});
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
    --el-dialog-padding-primary: 0px;
}

::v-deep .el-dialog__header {
    margin: 0;
    padding: 14px 20px;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
    }
}

::v-deep .el-dialog__body {
    padding: 20px;
}

::v-deep .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #f0f0f0;
}

.search-box {
    margin-bottom: 16px;

    .search-input {
        width: 240px;
    }
}

.pagination-box {
    margin-top: 16px;
    display: flex;
    justify-content: center;
}

:deep(.el-table) {
    --el-table-header-bg-color: #f8f9fa;
    --el-table-border-color: #ebeef5;
    --el-table-header-text-color: #606266;
    margin-bottom: 16px;
}

:deep(.el-radio) {
    margin-right: 0;
}

:deep(.el-button--primary) {
    --el-button-hover-bg-color: #4318ff;
    --el-button-hover-border-color: #4318ff;
}

:deep(.el-pagination) {
    --el-pagination-button-color: #606266;
    --el-pagination-button-bg-color: #fff;
    --el-pagination-button-hover-color: #626aef;
    --el-pagination-button-hover-bg-color: #f4f4f5;
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: #626aef !important;
    color: #fff;
}
</style>